package com.returnsoft.softphone.service;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

import javax.ejb.LocalBean;
import javax.ejb.Stateless;

import com.returnsoft.softphone.exception.CCenterExcepcion;

/**
 * Session Bean implementation class ManagerBean
 */
@Stateless
@LocalBean
public class ManagerBean implements ManagerInterface, Serializable {
	private static final long serialVersionUID = 1L;
	
	public String findPeer(String ipHost, String serverPbx, String managerUser, String managerPassword, Integer managerPort) throws CCenterExcepcion {

		try {
			
			System.out.println("ingreso a findPeer");
			System.out.println(serverPbx);
			System.out.println(managerUser);
			System.out.println(managerPassword);
			System.out.println(managerPort);
			System.out.println(ipHost);

			List<String> lines = new ArrayList<String>();

			InetAddress addr = InetAddress.getByName(serverPbx);

			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));
			String line = "";
			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");
			
			dos.writeBytes("Action: SIPpeers\r\n");

			//dos.writeBytes("Action: ExtensionState\r\n");
			//dos.writeBytes("Exten: " + peerName + "\r\n");
			// dos.writeBytes("ActionID: 2\r\n");
			dos.writeBytes("\r\n");

			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 3\r\n");
			dos.writeBytes("\r\n");
			List<String> filas = new ArrayList<String>();
			while (line != null) {
				// LOGGER.info("line: "+line);
				//System.out.println("line4: " + line);
				
				filas.add(line);
				if (line.equals("")) {
					System.out.println("cantidad de filas:"+filas.size());
					String peer="";
					for (String fila : filas) {
						System.out.println("fila:"+fila);
						if (fila.contains("ObjectName")) {
							peer=fila.substring(fila.indexOf(":")+1).trim();
						}
						if(fila.contains("IPaddress")){
							String ip = fila.substring(fila.indexOf(":")+1).trim();
							
							if (ip.equals(ipHost)) {
								System.out.println("ip"+ip);
								System.out.println("peer"+peer);
								socket.close();
								return peer;
							}
							
						}
					}
					filas = new ArrayList<String>();
				}
				lines.add(line);
				line = br.readLine();
			}

			socket.close();
			
			throw new CCenterExcepcion("No se encontro ningun peer en la ip: "+ipHost);

			/*if (lines.size() > 14) {
				String status = lines.get(14);
				// System.out.println("STATUS!!!" + status);
				return status;
			} else {
				throw new CustomExcepcion("Error al verificar estado del peer.");
			}*/

		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}

	}
	

	public String checkPeerStatus(String peerName, String serverPbx, String managerUser, String managerPassword, Integer managerPort) throws CCenterExcepcion {

		try {

			List<String> lines = new ArrayList<String>();

			InetAddress addr = InetAddress.getByName(serverPbx);

			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));
			String line = "";
			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");

			dos.writeBytes("Action: ExtensionState\r\n");
			dos.writeBytes("Exten: " + peerName + "\r\n");
			// dos.writeBytes("ActionID: 2\r\n");
			dos.writeBytes("\r\n");

			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 3\r\n");
			dos.writeBytes("\r\n");

			while (line != null) {
				// LOGGER.info("line: "+line);
				// System.out.println("line4: " + line);
				lines.add(line);
				line = br.readLine();
			}

			socket.close();

			if (lines.size() > 14) {
				String status = lines.get(14);
				// System.out.println("STATUS!!!" + status);
				return status;
			} else {
				throw new CCenterExcepcion("Error al verificar estado del peer.");
			}

		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}

	}
	
	
	public String addManyQueues(List<String> queues, String peerName, String serverPbx, String managerUser, String managerPassword, Integer managerPort)
			throws CCenterExcepcion {

		try {
			
			System.out.println("ingreso a addQueue");

			List<String> lines = new ArrayList<String>();

			InetAddress addr = InetAddress.getByName(serverPbx);
			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));
			String line = "";

			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");

			for (String queue : queues) {
				// System.out.println("en el for1:"+queue.getName());
				// System.out.println("en el for2:"+peer.getName());
				dos.writeBytes("Action: QueueAdd\r\n");
				dos.writeBytes("Queue: " + queue + "\r\n");
				dos.writeBytes("Interface: SIP/" + peerName + "\r\n");
				dos.writeBytes("Paused: false\r\n");
				dos.writeBytes("Priority: 1\r\n");
				// dos.writeBytes("ActionID: 3\r\n");
				dos.writeBytes("\r\n");

			}

			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 4\r\n");
			dos.writeBytes("\r\n");

			while (line != null) {
				 System.out.println("line1: " + line);
				lines.add(line);
				line = br.readLine();
			}
			socket.close();

			//System.out.println("Termino addQueue");

			//convertLinesToResponses(lines, queues);

			return "OK";

		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}
		

	}
	
	public String removeManyQueues(List<String> queues, String peerName, String serverPbx, String managerUser, String managerPassword, Integer managerPort)
			throws CCenterExcepcion {

		List<String> lines = new ArrayList<String>();

		try {

			InetAddress addr = InetAddress.getByName(serverPbx);
			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));

			String line = "";
			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");

			for (String queue : queues) {
				dos.writeBytes("Action: QueueRemove\r\n");
				dos.writeBytes("Queue: " + queue + "\r\n");
				dos.writeBytes("Interface: SIP/" + peerName + "\r\n");
				// dos.writeBytes("ActionID: 2\r\n");
				dos.writeBytes("\r\n");
			}

			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 3\r\n");
			dos.writeBytes("\r\n");
			while (line != null) {
				// LOGGER.info("line: "+line);
				System.out.println("line2: " + line);
				lines.add(line);
				line = br.readLine();
			}
			socket.close();
			
			
			return "OK";
			
		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}
	}
	
	public String pauseManyQueues(List<String> queues, String peerName, String serverPbx, String managerUser, String managerPassword, Integer managerPort)
			throws CCenterExcepcion {

		try {
			
			System.out.println("ingreso a pausemanyqueues");

			List<String> lines = new ArrayList<String>();

			InetAddress addr = InetAddress.getByName(serverPbx);

			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));

			String line = "";
			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");
			for (String queue : queues) {
				dos.writeBytes("Action: QueuePause\r\n");
				dos.writeBytes("Queue: " + queue + "\r\n");
				dos.writeBytes("Interface: SIP/" + peerName + "\r\n");
				dos.writeBytes("Paused: true\r\n");
				// dos.writeBytes("ActionID: 2\r\n");
				dos.writeBytes("\r\n");
			}
			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 3\r\n");
			dos.writeBytes("\r\n");
			while (line != null) {
				// LOGGER.info("line: "+line);
				 System.out.println("line3: " + line);
				lines.add(line);
				line = br.readLine();
			}
			socket.close();

			//return convertLinesToResponses(lines, queues);
			return "OK";

		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}

	}
	
	
	public String unpauseManyQueues(List<String> queues, String peerName, String serverPbx, String managerUser, String managerPassword, Integer managerPort)
			throws CCenterExcepcion {

		try {

			List<String> lines = new ArrayList<String>();

			InetAddress addr = InetAddress.getByName(serverPbx);

			SocketAddress sockaddr = new InetSocketAddress(addr, managerPort);
			Socket socket = new Socket();
			socket.connect(sockaddr);
			DataOutputStream dos = new DataOutputStream(
					socket.getOutputStream());
			DataInputStream dis = new DataInputStream(socket.getInputStream());
			BufferedReader br = new BufferedReader(new InputStreamReader(dis));

			String line = "";
			dos.writeBytes("Action: Login\r\n");
			dos.writeBytes("username: " + managerUser + "\r\n");
			dos.writeBytes("secret: " + managerPassword + "\r\n");
			// dos.writeBytes("ActionID: 1\r\n");
			dos.writeBytes("\r\n");
			for (String queue : queues) {
				dos.writeBytes("Action: QueuePause\r\n");
				dos.writeBytes("Queue: " + queue + "\r\n");
				dos.writeBytes("Interface: SIP/" + peerName + "\r\n");
				dos.writeBytes("Paused: false\r\n");
				// dos.writeBytes("ActionID: 2\r\n");
				dos.writeBytes("\r\n");
			}
			dos.writeBytes("Action: Logoff\r\n");
			// dos.writeBytes("ActionID: 3\r\n");
			dos.writeBytes("\r\n");
			while (line != null) {
				// LOGGER.info("line: "+line);
				 System.out.println("line4: " + line);
				lines.add(line);
				line = br.readLine();
			}
			socket.close();
			//return convertLinesToResponses(lines, queues);
			return "OK";

		} catch (UnknownHostException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (IOException e) {
			throw new CCenterExcepcion(e.getMessage());
		} catch (Exception e) {
			throw new CCenterExcepcion(e.getMessage());
		}

		

	}
	
}
